package com.app.util.memcached;

import java.util.Date;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class MemCached {

	// 创建全局的唯一实例
	private final MemCachedClient memCachedClient;
	private final MemCachedPoolConf memCachedPoolConf;

	/**
	 * 构造（设置与缓存服务器的连接池）
	 * 
	 * @param conf 
	 */
	public MemCached(MemCachedPoolConf memcachedConf) {
		this.memCachedPoolConf = memcachedConf;
		this.memCachedClient = new MemCachedClient();
		init(this.memCachedPoolConf);
	}

	private void init(MemCachedPoolConf memcachedConf) {
		// 获取socke连接池的实例对象
		SockIOPool pool = SockIOPool.getInstance();
		if (pool.isInitialized()) {
			return;
		}

		// 服务器列表和其权重，个人memcached地址和端口号
		pool.setServers(memcachedConf.servers);
		pool.setWeights(memcachedConf.weights);

		// 设置初始连接数、最小和最大连接数以及最大处理时间
		pool.setInitConn(memcachedConf.initConn);
		pool.setMinConn(memcachedConf.minConn);
		pool.setMaxConn(memcachedConf.maxConn);
		pool.setMaxIdle(memcachedConf.maxIdle);

		// 设置主线程的睡眠时间
		pool.setMaintSleep(memcachedConf.maintSleep);

		// 设置TCP的参数，连接超时等
		pool.setNagle(memcachedConf.nagle);
		pool.setSocketTO(memcachedConf.socketTO);
		pool.setSocketConnectTO(memcachedConf.socketConnectTO);

		// 初始化连接池
		pool.initialize();

		// 设置cache 数据的原始类型是String .默认值是false 只有在确定cache 的数据类型是string
		// 的情况下才设为true，这样可以加快处理速度。
		memCachedClient.setPrimitiveAsString(memcachedConf.primitiveAsString);
	}

	/**
	 * 添加一个指定的值到缓存中.
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(String key, Object value) {
		return memCachedClient.set(key, value);
	}

	/**
	 * 添加一个指定的值到缓存中.
	 * 
	 * @param key
	 * @param value
	 * @param expirySec
	 * @return
	 */
	public boolean set(String key, Object value, long expirySec) {
		return memCachedClient.set(key, value, toExpiryDate(expirySec));
	}

	/**
	 * 删除一个指定的值到缓存中.
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean delete(String key) {
		return memCachedClient.delete(key);
	}

	/**
	 * 根据指定的关键字获取对象.
	 * 
	 * @param key
	 * @return
	 */
	public Object get(String key) {
		return memCachedClient.get(key);
	}

	private Date toExpiryDate(long expirySec) {
		Date expiry = new Date(System.currentTimeMillis() + expirySec * 1000);
		return expiry;
	}

	public MemCachedPoolConf getMemCachedPoolConf() {
		return memCachedPoolConf;
	}

}